const express = require('express')
const { query } = require('../db')
const router = express.Router()

// 订单列表(get /)
router.get('/', async (req,res,next) => {
  const page = 10
  // 获取get传递的参数
  const obj = req.query
  console.log(obj)
  // 将一组条件进行拼接
  const arr = []
  for(let k in obj) {
    // 判断页码，并且有值的情况
    if(k !== 'pno' && obj[k]) {
      arr.push(`${k}='${obj[k]}'`)
    }
  }
  let str = arr.join(' && ')
  console.log(str)

  if(!obj.pno) {
    obj.pno = 1
  }
  let start = (obj.pno - 1) * page
  // 执行SQL命令
  try {
    var data = await query(`select a.id,a.num,b.uname,b.phone,b.sex,a.total,a.pay,a.pay_type,a.status,a.ctime,a.ptime,a.content,a.question,a.order_type from hs_order a,hs_user b where a.user_id=b.id ${str && ' && '+str} limit ${start},${page}; select count(*) as n from hs_order a,hs_user b where a.user_id=b.id ${str && ' && '+str}`)
  } catch(err) {
    return next(err)
  }
  console.log(data)
  res.send({
    code: 200,
    msg: '订单列表',
    data: data[0],
    total: data[1][0].n,
    pno: obj.pno
  })
})

module.exports = router